package com.tang.lts.core.nio.handler;


import com.tang.lts.remoting.Future;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Tang
 * @classname IoFuture
 * @description [  ]
 * @date 2022/5/15 15:43
 */
public class IoFuture implements Future {

    private boolean success = false;
    private Throwable cause;
    private boolean done = false;

    private List<IoFutureListener> listeners;

    private final Object lock = this;

    public void addListener(IoFutureListener listener) {
        if (listener == null) {
            return;
        }
        synchronized (lock) {
            if (listeners == null) {
                listeners = new ArrayList<>();
            }
            listeners.add(listener);
            if (isDone()) {
                complete(listener);
            }
        }
    }

    private void complete(IoFutureListener listener) {
        try {
            listener.operationComplete(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean isDone() {
        return done;
    }

    public void setDone(boolean done) {
        this.done = done;
    }

    public void notifyListeners() {
        synchronized (this) {
            done = true;
            if (this.listeners != null) {
                for (IoFutureListener listener : listeners) {
                    complete(listener);
                }
            }
        }
    }

    @Override
    public boolean isSuccess() {
        return success;
    }

    @Override
    public Throwable cause() {
        return cause;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public void setCause(Throwable cause) {
        this.cause = cause;
    }
}